package com.campus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.campus.constant.MessageConstant;
import com.campus.exception.SubjectException;
import com.campus.mapper.SubjectMapper;
import com.campus.pojo.dto.SubjectDTO;
import com.campus.pojo.po.Subject;
import com.campus.pojo.vo.SubjectVO;
import com.campus.service.SubjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@RequiredArgsConstructor
public class SubjectImpl implements SubjectService {

    //科目
    private final SubjectMapper subjectMapper;

    /**
     * 获取全部科目
     * @return
     */
    @Override
    public List<SubjectVO> getAllSubjects() {
        List<Subject> subjects = subjectMapper.getAllSubjects();
        return BeanUtil.copyToList(subjects,SubjectVO.class);
    }

    /**
     * 根据id删除学科
     * @param id
     */
    @Override
    public void deleteSubject(Integer id) {
        subjectMapper.deleteSubjectById(id);
    }

    /**
     * 添加学科
     */
    @Override
    public void addSubject(SubjectDTO subjectDTO) {
        //检查学科是否已经存在
        Integer count = subjectMapper.checkExist(subjectDTO.getName());
        if ( count >= 1 ){
            //学科已经存在，抛出异常
            throw new SubjectException(MessageConstant.SUBJECT_EXISTED);
        }
        Subject subject = new Subject();
        BeanUtils.copyProperties(subjectDTO, subject);
        subjectMapper.addSubject(subject);
    }

    /**
     * 更新学科
     * @param subjectDTO
     */
    @Override
    public void updateSubject(SubjectDTO subjectDTO) {
        //检查数据
        if (subjectDTO.getId() == null || subjectDTO.getName().isBlank()){
            throw new SubjectException(MessageConstant.SUBJECT_ID_OR_NAME_NULL);
        }

        Subject subject = new Subject();
        BeanUtils.copyProperties(subjectDTO, subject);

        subjectMapper.updateSubject(subject);
    }
}
